let visitModule = (function () {
    let $tableBox = $('.tableBox'),
        $tbody = $tableBox.find('tbody'),
        $visitTime = $('.visitTime'),
        $visitText = $('.visitText'),
        $submit = $('.submit')
    let customerId = null
    async function submitHandle() {  
        let result = await axios.post('/visit/add', {
            customerId,
            visitText: $visitText.val().trim(),
            visitTime: $visitTime.val()
        })
        if (result.code == 0) {
            alert('添加成功')
            bindHTML()
            return
        }
        alert('添加失败') 
    }
    async function bindHTML() {
        let result = await axios.get('/visit/list', { params: { customerId: customerId } })
        if (result.code == 0) {
            let str = ``
            result = result.data
            result.forEach((item,index) => { 
                let {id, customerId, customerName, visitText, visitTime } = item
                str+=`<tr>
					<td class="w5">${index+1}</td>
					<td class="w15">${visitTime}</td>
					<td class="w70 wrap">${visitText}</td>
					<td class="w10">
						<a href="javascript:;" visitId="${id}" class="btnDelete">删除</a>
					</td>
				</tr>`
            })
            $tbody.html(str) 
        } 
    }
    async function delegateHandle() {
        $tbody.click(async ev => {
            let target = ev.target,
                $target = $(target) 
            let id = $target.attr('visitId')
            if (target.className === "btnDelete") {
                let flag = confirm('确定删除吗？')
                if(!flag) return
                let result = await axios.get('/visit/delete', { params: { visitId: id } })
                if (result.code == 0) {
                    alert('删除成功')
                    bindHTML()
                }
            }
        })
    }
    return {
        init() {
            let params = window.location.href.queryURLParams()
            params.id ? customerId = params.id : null
            bindHTML()
            $submit.click(submitHandle)
            delegateHandle()
        }
    }
})()
visitModule.init()